package main

import (
	"AdvanceGo/12_grpc/service"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/types/known/wrapperspb"
	"log"
	"net"
)

// ProductService 业务逻辑结构体
// 将 UnimplementedProductServiceServer 作为匿名字段
type ProductService struct {
	service.UnimplementedProductServiceServer
}

// GetProductStock 实现业务逻辑
func (p *ProductService) GetProductStock(ctx context.Context, request *service.ProductRequest) (*service.ProductResponse, error) {
	log.Println("request:", request.String())
	return &service.ProductResponse{
		ProdStockId: 10,
		// 注意返回的值：{username:"James" age:18 high:{value:175}}
		User: &service.User{
			Username: "James",
			Age:      18,
			High:     wrapperspb.Int32(175),
		},
	}, nil
}

func main() {
	// 监听端口
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 8999))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	// 创建服务
	s := grpc.NewServer()
	// 注册服务
	service.RegisterProductServiceServer(s, &ProductService{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
